#pragma once

#include <iostream>
#include <unistd.h>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include "Thread.hpp"
#include "Log.hpp"
#include "LockGuard.hpp"

using namespace ThreadMoudle;
using namespace log_ns;

static const int gdefaultnum = 5; // 默认创建5个线程

void test()
{
    while (true)
    {
        std::cout << "hello world" << std::endl;
        sleep(1);
    }
}

template <typename T>
class ThreadPool
{
private:
    // 任务队列加锁
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnlockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }
    // 唤醒一个线程
    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    // 唤醒所有线程
    void WakeupAll()
    {
        pthread_cond_broadcast(&_cond);
    }
    // 休眠
    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    bool IsEmpty()
    {
        return _task_queue.empty();
    }
    // 处理任务，从任务队列取任务，加锁
    void HandlerTask(const std::string &name)
    {
        while (true)
        {
            // 1.取任务
            LockQueue();
            // 队列为空且运行则休眠
            while (IsEmpty() && _isrunning) // if?
            {
                _sleep_thread_num++; // 防止阻塞，因为一开始休眠线程数为0
                LOG(INFO, "%s thread sleep begin!\n", name.c_str());
                Sleep();
                LOG(INFO, "%s thread wakeup!\n", name.c_str());
                _sleep_thread_num--;
            }
            // 判定一种情况，为空且不运行则退出
            if (IsEmpty() && !_isrunning)
            {
                LOG(INFO, "%s thread quit!\n", name.c_str());
                UnlockQueue();
                break;
            }
            // 有任务
            T t = _task_queue.front();
            _task_queue.pop();
            UnlockQueue();

            // 2.处理任务
            t(); // 处理任务(只属于自己线程)，此处不用/不能在临界区处理
        }
    }
    // 单例模式构造函数私有
    ThreadPool(int thread_num = gdefaultnum)
        : _thread_num(thread_num), _isrunning(false), _sleep_thread_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    void Init()
    {
        func_t func = std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1); // 绑定
        for (int i = 0; i < _thread_num; i++)
        {
            std::string threadname = "thread-" + std::to_string(i + 1);
            _threads.emplace_back(threadname, func);
            LOG(DEBUG, "construct thread %s done,init success\n", threadname.c_str());
        }
    }
    void Start()
    {
        _isrunning = true;
        for (auto &thread : _threads)
        {
            LOG(DEBUG, "start thread %s done.\n", thread.Name().c_str());
            thread.Start();
        }
    }
    ThreadPool(const ThreadPool<T> &) = delete;     // 禁止拷贝构造
    void operator=(const ThreadPool<T> &) = delete; // 禁止赋值重载
public:
    void Stop()
    {
        LockQueue();
        _isrunning = false;
        WakeupAll(); // 防止有线程在等待
        UnlockQueue();
        LOG(INFO, "thread pool stop done!\n");
    }

    // 如果是多线程获取单例呢？
    static ThreadPool<T> *GetInstance()
    {
        // 只有第一次需要加锁，减少锁的竞争
        if (_tp == nullptr)
        {

            LockGuard lockguard(&_sig_mutex);
            if (_tp == nullptr)
            {
                LOG(INFO, "create thread pool\n");
                _tp = new ThreadPool<T>();
                _tp->Init();
                _tp->Start();
            }
            else
            {
                LOG(INFO, "get thread pool\n");
            }
        }
        return _tp;
    }
    void Equeue(const T &in)
    {
        LockQueue();
        // 防止false情况还一直在入队列
        if (_isrunning)
        {
            _task_queue.push(in);
            // 唤醒线程，有休眠的就唤醒
            if (_sleep_thread_num > 0)
                Wakeup();
        }
        UnlockQueue();
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _thread_num;
    std::vector<Thread> _threads;
    std::queue<T> _task_queue; // 任务队列，共享资源，需要保护
    bool _isrunning;

    int _sleep_thread_num; // 休眠线程个数

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    // 单例模式
    static ThreadPool<T> *_tp;
    static pthread_mutex_t _sig_mutex;
};

// 静态成员类外初始化
template <typename T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;

template <typename T>
pthread_mutex_t ThreadPool<T>::_sig_mutex = PTHREAD_MUTEX_INITIALIZER;